<template>
  <div class="baseinfo">
    <p-form-model
    ref="ruleForm"
    :model="form"
    :rules="rules"
  >
    <div>
      <p-form-model-item label="产品编码" prop="productCode">
        <p-popover :style="{'pointer-events':(handle === 'edit' || handle === 'look')?'none':'all'}" v-model="popoverShow" placement="bottomLeft" trigger="click">
          <template slot="content">
            <div style="display:flex;align-items: center;margin-bottom: 10px;">
              <div style="width:240px;">
                <p-input-search
                  allowClear
                  @change="popSearch"
                  v-model="popPagination.keyword"
                  :placeholder="'请输入产品编码或者名称'"
                />
              </div>
              <p-button
                type="primary"
                style="margin-left:10px;"
                @click="popSearch"
              >
                搜索
              </p-button>
            </div>
            <p-table
              style="width: inherit;"
              ref="tableRef"
              :customRow="popCustomRow"
              :rowClassName="popRowClassName"
              :data-source="popTableData"
              :columns="popColumns"
              :pagination="popPagination"
              row-key="id"
              :scroll="{ x:400, y: 400 }"
              @change="popTableChange"
            >
            </p-table>
          </template>
          <p-select :disabled="handle === 'edit' || handle === 'look'" v-model="form.productCode" :filterOption="false" :not-found-content="null">
          <!-- <p-select show-search v-model="form.productCode" @change="codeChange" :filterOption="filterOption"> -->
            <!-- <p-select-option 
              :value="item.mcode"
              v-for="(item, index) in []" 
              :key="item.mcode">
              {{item.mcode}}
            </p-select-option> -->
          </p-select>
        </p-popover>
        
      </p-form-model-item>
        <p-form-model-item label="产品名称" prop="productName">
        <p-input
          disabled
          placeholder="请输入内容"
          v-model="form.productName"
        />
      </p-form-model-item>
      <p-form-model-item label="产品描述" prop="productSpec">
        <p-input
          disabled
          placeholder="请输入内容"
          v-model="form.productSpec"
        />
      </p-form-model-item>
    </div>
    <div>
      <p-form-model-item label="工艺路线类型" prop="routeType">
        <p-select v-model="form.routeType">
          <p-select-option :value="item.value" v-for="(item, index) in routeTypeList" :key="item.value">
            {{item.text}}
          </p-select-option>
        </p-select>
      </p-form-model-item>
      <p-form-model-item label="工艺路线编码" prop="routeCode">
        <p-input disabled
          placeholder="请输入内容"
          v-model="form.routeCode"
        />
      </p-form-model-item>
      <div class="handleBtnWrap">
        <p-button class="handleBtn" @click="clickWorkingHour" type="primary">工时调整</p-button>
        <p-button class="handleBtn" @click="clickSopMaterial" type="primary" >物料分配</p-button>
        <p-button class="handleBtn" @click="clickSopCover" type="primary">SOP封面</p-button>
      </div>
    </div>
    <div>
      <p-form-model-item label="工艺路线描述" prop="routeDes">
        <p-input
          placeholder="请输入内容"
          v-model="form.routeDes"
        />
      </p-form-model-item>
      <p-form-model-item label="工艺路线名称" prop="routeName">
        <p-input
          placeholder="请输入内容"
          v-model="form.routeName"
        />
      </p-form-model-item>
    </div>
  </p-form-model>
    <div class="submitBtn">
      <p-button class="handleBtn" style="margin-right: 20px;" @click="$parent.processHandleCancel">取消</p-button>
      <p-button :loading="$parent.loading" v-if="look !== '1'" class="handleBtn" @click="$parent.processHandleConfirm" type="primary">确认</p-button>
    </div>
    <component :is="componentId" :options="options" v-model="visible" @callback="callback"></component>
  </div>
</template>

<script>
import mesPeProcess from "@/api/mesPeProcess";
import sopCover from "../../components/sopCover/index.vue";
import sopMaterial from "../../components/sopMaterial/index.vue";
import workingHour from "../../components/workingHour/index.vue";
import _ from "lodash";
import mixins from './mixins'
export default {
  name: "handleProcess",
  mixins: [mixins],
  components: {
    sopCover,
    sopMaterial,
    workingHour,
  },
  props: {
    pdata: Object, 
  },
  data() {
    return {
      visible: false,
      popoverShow: false,
      sopCoverModel: false,
      sopMaterialModel: false,
      labelCol: { span: 3 },
      wrapperCol: { span: 8 },
      other: '',
      productCodeList: [],
      routeTypeList: [],
      popTableData: [],
      popColumns: [
        {
          title: '产品编码',
          align: 'center',
          width: 200,
          dataIndex: 'mcode'
        },
        {
          title: '产品名称',
          align: 'center',
          dataIndex: 'mname',
          ellipsis: true
        },
      ],
      popPagination: {
        keyword: '',
        current: 1,
        total: 0,
        pageSize: 10, // 每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], // 每页中显示的数据
        showTotal: total => `共 ${total} 条` // 分页中显示总的数据
      },
      form: {
        // 基本信息
        productCode: '', // 产品编码
        routeCode: '', // 工艺路线编码
        routeType: '', // 工艺路线类型
        productName: '',  // 产品名称
        routeName: '', // 工艺路线名称
        productSpec: '', // 产品描述
        routeDes: '', // 工艺路线描述
        version: '', // 工艺路线版本
        // 封面制作
        sendCom: '', // 发文单位
        useCom: '', // 使用单位
        preparedBy: '', // 编制人
        approvedBy: '', // 审批人
        designFileCode: '', //设计文件编号
      },
      sopCover: {},
      rules: {
        productCode: [
          { required: true, message: '请输内容', trigger: 'change' },
        ],
        routeCode: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        routeType: [
          { required: true, message: '请输内容', trigger: 'change' },
        ],
        productName: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        routeName: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        productSpec: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        routeDes: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    title(){
      return this.handle === 'add'?'新增产品工艺路线':'修改产品工艺路线'
    },
    handle(){
      return this.$route.query.handle
    },
    curPens(){
      return this.$parent.$refs.DrawRoute.canvas.data.pens;
    },
    look(){
      return this.$route.query.look
    }
  },
  created() {
    if ( this.handle === 'edit' || this.handle === 'addAndEdit' ){
      // 基本信息
      this.form.productCode = this.pdata.mcode;
      this.form.productName = this.pdata.mname;
      this.form.productSpec = this.pdata.sprc;
      this.form.routeType = this.pdata.routerType + '';
      this.form.routeCode = this.pdata.routerCode;
      this.form.routeDes = this.pdata.routerDesc;
      this.form.routeName = this.pdata.routerName;
      this.form.version = this.pdata.version;
      // 封面制作
      this.form.sendCom = this.pdata.sendCom;
      this.form.useCom = this.pdata.useCom;
      this.form.preparedBy = this.pdata.preparedBy;
      this.form.approvedBy = this.pdata.approvedBy;
      this.form.designFileCode = this.pdata.designFileCode;
      // 保存到vuex
      this.$store.commit('setBaseInfo', this.form);
    }
    this.queryNotMaterielPage();
    this.sysDictItem();
  },
  methods: {
    popRowClassName(record, index){ 
      return record.choose?'popCodeChooseClass':'';
    },
    popCustomRow(record, index){
      const that = this;
      return {
        style:{
          cursor: 'pointer',
        },
        on: {
          // 鼠标单击行
          click: event => {
            that.popTableData.forEach( (el, ind) =>{
              el.choose = ind === index;
            });
            that.form.productCode = record.mcode;
            that.form.productName = record.mname;
            that.form.productSpec = record.mexplain;
            // 保存到vuex
            this.$store.commit('setBaseInfo', this.form);
            that.getRouteCodeByProductCode(record.mcode);
            that.popoverShow = false;
            // that.$refs.ruleForm.validate();
          },
        },
      }
    },
    popSearch(){
      this.popPagination.current = 1;
      this.popPagination.pageSize = 10;
      this.queryNotMaterielPage();
    },
    popTableChange (pageOptions) {
      this.popPagination.current = pageOptions.current;
      this.popPagination.pageSize = pageOptions.pageSize;
      this.queryNotMaterielPage();
    },
    callback(data, type){
      console.log(data, type);
      const canvas = this.$parent.$refs.DrawRoute.canvas;
      /* if ( !(data && canvas && canvas.data && canvas.data.pens && canvas.data.pens.length > 0) ){
        return;
      } */
      if ( type === 'workingHour'){
        let configTree = [];
        data.forEach( el =>{
          configTree = configTree.concat(el.children);
        });
        this.$parent.$refs.DrawRoute.canvas.data.pens.forEach( element =>{
          if ( element.data && element.data.key === 'process' ){
            element.data.configTree.forEach(elem => {
              let item = configTree.filter( el => el.id === elem.id);
              item = item[0];
              elem.hour = item.hour;
              elem.children.forEach(el => {
                item.children.forEach( e =>{
                  if ( e.id === el.id ){
                    el.hour = e.hour;
                    el.siteAttr.workstationHour = e.hour;
                  }
                });
              });
            });
          }
        });
      }else if( type === 'sopMaterial' ){
        // 筛选出工站物料，剔除主物料
        const bomData = data.filter( el => el.workstationCode !== null );
        const bomDataMap = {};
        bomData.forEach( el =>{
          delete el.parent;
          if ( !bomDataMap[el.workstationCode] ){
            bomDataMap[el.workstationCode] = [el];
          }else {
            bomDataMap[el.workstationCode].push(el);
          }
        });
        let curBomData = [];
        this.$parent.$refs.DrawRoute.canvas.data.pens.forEach( (element,elementIndex) =>{
          if ( element.data && element.data.key === 'process' ){
            element.data.configTree.forEach((elem, elemIndex) => {
              elem.children.forEach((ele, eleIndex) => {
                let curArr = bomDataMap[ele.siteAttr.workstationCode] || [];
                ele.bomData = ele.bomData.filter((cEl,index) => {
                  return !!(curArr.find(tl => tl.mcode === cEl.mcode));
                })
                // 某一个工站的Bom
                ele.bomData.forEach( el =>{
                  // 所有工站的Bom 匹配每一个当前工站下的
                  bomData.forEach(e => {
                    if ( ele.siteAttr.workstationCode === e.workstationCode && el.mcode === e.mcode ){
                      el.stationsRequired = e.stationsRequired;
                      el.maintenanceKey = e.maintenanceKey;
                    }
                  });
                });
                curBomData = ele.bomData;
              });
            });
          }
        });
        this.calcuAndUpdateRemainQuantity();
        this.evBus.$emit('refreshBomData',{
          drawRoute: this.$parent.$refs.DrawRoute,
          curBomData,
        }); 
      }else if(type === 'sopCover'){
        this.form = data;
      }
    },
    clickWorkingHour(){
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.options = {
            data: this.$parent.$refs.DrawRoute.getWorkingHour(),
            form: _.cloneDeep(this.form),
          };
          this.componentId = 'workingHour';
          this.visible = true;
        }
      });
    },
    clickSopCover(){
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.visible = true;
          this.componentId = 'sopCover';
          this.options = _.cloneDeep(this.form);
        }
      });
    },
    clickSopMaterial(){
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.options = {
            data: this.$parent.$refs.DrawRoute.getMaterial(),
            form: _.cloneDeep(this.form),
            treeData: _.cloneDeep(this.$parent.$refs.DrawRoute.getWorkingHour()),
          };
          this.visible = true;
          this.componentId = 'sopMaterial';
        }
      }); 
    },
    codeChange(val){
      const curItem = this.productCodeList.filter( el => el.mcode === val );
      this.form.productName = curItem[0].mname;
      this.form.productSpec = curItem[0].mexplain;
      this.getRouteCodeByProductCode(val);
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    sysDictItem(){
      mesPeProcess.sysDictItem('gylxzx').then( res =>{
          if (res.code === 0){
            const curData = res.data || [];
            this.routeTypeList = res.data || [];
            if (this.routeTypeList.length > 0 && this.form.routeType === ''){
              this.form.routeType = this.routeTypeList[0].value;
            }
          }
      });
    },
    getRouteCodeByProductCode(productCode){
      mesPeProcess.getRouteCodeByProductCode({productCode}).then( res =>{
          if (res.code === 0){
            this.form.routeCode = res.data.routerCode;
            this.form.version = res.data.version;
            // 保存到vuex
            this.$store.commit('setBaseInfo', this.form);
          }
      });
    },
    queryNotMaterielPage(){
      const {current,pageSize,keyword} = this.popPagination;
      mesPeProcess.queryNotMaterielPage({
        pageNo: current,
        limit: pageSize,
        keyword,
      }).then( res =>{
          if (res.code === 0){
            const curData = res.data.records || [];
            this.popTableData = curData;
            this.popPagination.total = res.data.total;
            /* if (curData.length > 0){
              this.form.productCode = curData[0].mcode;
              this.form.productName = curData[0].mname;
              this.form.productSpec = curData[0].mexplain;
              this.getRouteCodeByProductCode(this.form.productCode);
            } */
          }
      });
    },
  },
};
</script>
<style scoped lang='less'>
.baseinfo{
  margin-top: 20px;
  .poros-form{
    display: flex;
    >div{
      width: 400px;
      &+div{
        margin-left: 30px;
      }
    }
    .poros-form-item{
      display: flex;
    }
    /deep/ .poros-form-item-label{
      width: 110px;
    }
  }
  .handleBtnWrap{
    /* height: 40px;
    display: flex;
    align-items: center;
    justify-content: flex-start; */
    padding-top: 3px;
  }
  .handleBtn{
    margin-right: 10px;
  }
  /deep/ .poros-select-disabled{
    color: #000;
  }
  .submitBtn{
    text-align: center;
    margin-top: 20px;
  }
}
.custRow{
  cursor: pointer;
}
</style>
<style lang='less'>
.popCodeChooseClass{
  td{
    background-color: #9fd3fd !important;
  }
}
</style>